<?php

namespace app\store\controller;

use app\store\model\CurrencyDetailModel;
use app\store\model\GameCurrencyModel;
use library\Controller;
use library\tools\Express;
use think\Db;

/**
 * 货币
 * Class Currency
 * @package app\store\controller
 */
class Currency extends Controller
{
    /**
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $request = input('request.');
        $list = GameCurrencyModel::where($this->structure_where())
            ->order('time desc')
            ->paginate(20, false, ['query' => $request])->each(function ($item, $key) {
                if ($item->SpreaderID == 888) {
                    $item->channel_name = '全部渠道';
                } else if ($item->SpreaderID == 0) {
                    $item->channel_name = '官方-0-渠道';
                } else {
                    $item->channel_name = get_channel_name($item->SpreaderID);
                }
            });

        $pages = $list->render();
        /*渠道类型*/
        $channel_arr = Specific_parameters_Recharge_channel_arr();
        $start_time = date('Y-m-d', time() - 7 * 24 * 3600) . ' - ' . date('Y-m-d', time() - 24 * 3600);

        $this->assign('start_time', $start_time);
        $this->assign('channel_arr', $channel_arr);
        $this->assign('list', $list);
        $this->assign('pages', $pages);
        $this->fetch();
    }

    /**
     * 详细
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        $list = CurrencyDetailModel::fieldRaw('type,get_method,sum(receive) as receive,sum(consume) as consume')->where($this->structure_where_detail())
            ->group('type,get_method')
            ->order('type asc,get_method desc,receive desc')
            ->select()->toArray();
// var_dump($list);
        $data = [
            1 => [
                'receive' => ['types' => [], 'title' => '金币产出'],
                'consume' => ['types' => [], 'title' => '金币消耗'],
            ],
            2 => [
                'receive' => ['types' => [], 'title' => '钻石产出'],
                'consume' => ['types' => [], 'title' => '钻石消耗'],
            ],
            3 => [
                'receive' => ['types' => [], 'title' => '鱼券产出'],
                'consume' => ['types' => [], 'title' => '鱼券消耗'],
            ],
            4 => [
                'receive' => ['types' => [], 'title' => '弹头产出'],
                'consume' => ['types' => [], 'title' => '弹头消耗'],
            ]
        ];


        foreach ($list as $k => $v) {

            if($v['get_method'] == '大厅_0'){
                $data[$v['type']]['receive']['types']['房间外'] = $v['receive'];
                $data[$v['type']]['consume']['types']['房间外'] = $v['consume'];
            }else{
                // 对所有的房间进行求和放到结果中
                if(array_key_exists($v['get_method'],CurrencyDetailModel::ALL_ROOMS)){
                    if(!isset($data[$v['type']]['receive']['types']['房间内'])){
                        $data[$v['type']]['receive']['types']['房间内'] = $v['receive'];
                        $data[$v['type']]['consume']['types']['房间内'] = $v['consume'];
                    }else{
                        $data[$v['type']]['receive']['types']['房间内'] += $v['receive'];
                        $data[$v['type']]['consume']['types']['房间内'] += $v['consume'];
                    }
                }
                $data[$v['type']]['receive']['types'][CurrencyDetailModel::$all_method[$v['get_method']]] = $v['receive'];
                $data[$v['type']]['consume']['types'][CurrencyDetailModel::$all_method[$v['get_method']]] = $v['consume'];
            }
        }

        // var_dump($data[3]);die;

        /*渠道类型*/
        $channel_arr = Specific_parameters_Recharge_channel_arr();
        $start_time = date('Y-m-d', time() - 7 * 24 * 3600) . ' - ' . date('Y-m-d', time() - 24 * 3600);
        // var_dump($data);die;
        $this->assign('start_time', $start_time);
        $this->assign('channel_arr', $channel_arr);
        $this->assign('list', $data);
        $this->fetch();
    }

    protected function structure_where()
    {
        $type = $this->request->param('type');
        $channel = $this->request->param('channel');
        $search_time = $this->request->param('search_time');
        $where = [];
        if (!empty($search_time)) {
            $list = explode(' - ', $search_time);
            $begin = $list[0];
            $after = $list[1];
        } else {
            $begin = date('Y-m-d', time() - 7 * 24 * 3600);
            $after = date('Y-m-d', time() - 24 * 3600);
        }

        if (empty($type)) {
            $type = 1;
        }

        $where[] = ['time', 'between', [$begin, $after]];
        $where[] = ['type', '=', $type];

        if (!empty($channel)) {
            if ($channel == 30) $channel = 0;
            $where[] = ['SpreaderID', 'eq', $channel];
        } else {
            $where[] = ['SpreaderID', 'eq', 888];
        }
        return $where;
    }

    protected function structure_where_detail()
    {
        $search_time = $this->request->param('search_time');
        $where = [];
        if (!empty($search_time)) {
            $list = explode(' - ', $search_time);
            $begin = $list[0];
            $after = $list[1];
        } else {
            $begin = date('Y-m-d', time() - 7 * 24 * 3600);
            $after = date('Y-m-d', time() - 24 * 3600);
        }

        $where[] = ['time', 'between', [$begin, $after]];

        return $where;
    }

    /**
     * 订单列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _index_page_filter(array &$data)
    {
        $goodsList = Db::name('StoreOrderList')->whereIn('order_no', array_unique(array_column($data, 'order_no')))->select();
        $mids = array_unique(array_merge(array_column($data, 'mid'), array_column($data, 'from_mid')));
        $memberList = Db::name('StoreMember')->whereIn('id', $mids)->select();
        foreach ($data as &$vo) {
            list($vo['member'], $vo['from_member'], $vo['list']) = [[], [], []];
            foreach ($goodsList as $goods) if ($goods['order_no'] === $vo['order_no']) {
                $vo['list'][] = $goods;
            }
            foreach ($memberList as $member) if ($member['id'] === $vo['mid']) {
                $vo['member'] = $member;
            }
        }
    }

    /**
     * 修改快递管理
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function express()
    {
        if ($this->request->isGet()) {
            $where = ['is_deleted' => '0', 'status' => '1'];
            $this->expressList = Db::name('StoreExpress')->where($where)->order('sort desc,id desc')->select();
        }
        $this->_form($this->table);
    }

    /**
     * 快递追踪查询
     * @auth true
     */
    public function expressQuery()
    {
        list($code, $no) = [input('code', ''), input('no', '')];
        if (empty($no)) $this->error('快递编号不能为空！');
        if (empty($code)) $this->error('快递公司编码不能为空！');
        $this->result = Express::query($code, $no);
        $this->fetch();
    }

    /**
     * 快递表单处理
     * @param array $vo
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _express_form_filter(&$vo)
    {
        if ($this->request->isPost()) {
            $order = Db::name($this->table)->where(['id' => $vo['id']])->find();
            if (empty($order)) $this->error('订单查询异常，请稍候再试！');
            $express = Db::name('StoreExpress')->where(['express_code' => $vo['express_company_code']])->find();
            if (empty($express)) $this->error('发货快递公司异常，请重新选择快递公司！');
            $vo['express_company_title'] = $express['express_title'];
            $vo['express_send_at'] = empty($order['express_send_at']) ? date('Y-m-d H:i:s') : $order['express_send_at'];
            $vo['express_state'] = '1';
            $vo['status'] = '4';
        }
    }

}
